package services

import (
	"domain-system/models"
	"errors"
	"time"

	"gorm.io/gorm"
)

type PaymentService struct {
	db *gorm.DB
}

func NewPaymentService(db *gorm.DB) *PaymentService {
	return &PaymentService{db: db}
}

// CheckPaymentStatus 检查支付状态
func (s *PaymentService) CheckPaymentStatus(groupID, applicantID string) (*PaymentStatusResponse, error) {
	var application models.GroupApplication

	// 查找群申请记录，包含支付信息
	err := s.db.Preload("Payment").Where("group_id = ? AND applicant_id = ?", groupID, applicantID).First(&application).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return &PaymentStatusResponse{
				GroupID:     groupID,
				ApplicantID: applicantID,
				HasPaid:     false,
				Status:      string(models.PaymentStatusPending),
				Message:     "未找到申请记录",
			}, nil
		}
		return nil, err
	}

	response := &PaymentStatusResponse{
		GroupID:     groupID,
		ApplicantID: applicantID,
		HasPaid:     false,
		Status:      string(models.PaymentStatusPending),
	}

	// 如果有关联的支付记录
	if application.Payment != nil {
		payment := application.Payment
		response.PaymentID = payment.TransactionID
		response.Amount = payment.Amount
		response.Status = string(payment.Status)
		response.PaymentMethod = payment.PaymentMethod

		if payment.PaymentTime != nil {
			response.PaymentTime = payment.PaymentTime
		}

		// 判断是否已支付
		if payment.Status == models.PaymentStatusPaid {
			response.HasPaid = true
			response.Message = "支付成功"
		} else {
			response.Message = s.getStatusMessage(payment.Status)
		}
	} else {
		response.Message = "未创建支付记录"
	}

	return response, nil
}

// CreatePayment 创建支付记录
func (s *PaymentService) CreatePayment(req *CreatePaymentRequest) (*models.Payment, error) {
	// 检查是否已存在支付记录
	var existingPayment models.Payment
	err := s.db.Where("group_id = ? AND applicant_id = ?", req.GroupID, req.ApplicantID).First(&existingPayment).Error
	if err == nil {
		return nil, errors.New("该用户已存在支付记录")
	}

	// 创建新的支付记录
	payment := &models.Payment{
		GroupID:       req.GroupID,
		ApplicantID:   req.ApplicantID,
		Amount:        req.Amount,
		Status:        models.PaymentStatusPending,
		PaymentMethod: req.PaymentMethod,
		TransactionID: req.TransactionID,
		Description:   req.Description,
	}

	if err := s.db.Create(payment).Error; err != nil {
		return nil, err
	}

	// 创建或更新群申请记录
	var application models.GroupApplication
	err = s.db.Where("group_id = ? AND applicant_id = ?", req.GroupID, req.ApplicantID).First(&application).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		// 创建新的申请记录
		application = models.GroupApplication{
			GroupID:     req.GroupID,
			ApplicantID: req.ApplicantID,
			PaymentID:   &payment.ID,
			Status:      "pending",
			AppliedAt:   time.Now(),
		}
		s.db.Create(&application)
	} else {
		// 更新现有申请记录
		application.PaymentID = &payment.ID
		s.db.Save(&application)
	}

	return payment, nil
}

// UpdatePaymentStatus 更新支付状态
func (s *PaymentService) UpdatePaymentStatus(transactionID string, status models.PaymentStatus) error {
	updates := map[string]interface{}{
		"status": status,
	}

	if status == models.PaymentStatusPaid {
		now := time.Now()
		updates["payment_time"] = &now
	}

	return s.db.Model(&models.Payment{}).Where("transaction_id = ?", transactionID).Updates(updates).Error
}

// getStatusMessage 获取状态描述
func (s *PaymentService) getStatusMessage(status models.PaymentStatus) string {
	switch status {
	case models.PaymentStatusPending:
		return "等待支付"
	case models.PaymentStatusPaid:
		return "支付成功"
	case models.PaymentStatusFailed:
		return "支付失败"
	case models.PaymentStatusRefunded:
		return "已退款"
	case models.PaymentStatusCancelled:
		return "支付已取消"
	default:
		return "未知状态"
	}
}

// PaymentStatusResponse 支付状态响应
type PaymentStatusResponse struct {
	GroupID       string     `json:"group_id"`
	ApplicantID   string     `json:"applicant_id"`
	HasPaid       bool       `json:"has_paid"`
	Status        string     `json:"status"`
	PaymentID     string     `json:"payment_id,omitempty"`
	Amount        float64    `json:"amount,omitempty"`
	PaymentMethod string     `json:"payment_method,omitempty"`
	PaymentTime   *time.Time `json:"payment_time,omitempty"`
	Message       string     `json:"message"`
}

// CreatePaymentRequest 创建支付请求
type CreatePaymentRequest struct {
	GroupID       string  `json:"group_id" binding:"required"`
	ApplicantID   string  `json:"applicant_id" binding:"required"`
	Amount        float64 `json:"amount" binding:"required,gt=0"`
	PaymentMethod string  `json:"payment_method"`
	TransactionID string  `json:"transaction_id" binding:"required"`
	Description   string  `json:"description"`
}
